package com.site.common.validator;

import com.site.common.validator.annotation.DateFormat;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/** 自定义时间验证器
 * @author xiaochi
 * @date 2022/5/20 16:15
 * @desc DateFormatValidator
 */
public class DateFormatValidator implements ConstraintValidator<DateFormat, Date> {

    private DateFormat dateFormat;

    @Override
    public void initialize(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }

    @Override
    public boolean isValid(Date date, ConstraintValidatorContext constraintValidatorContext) {
        try {// 如果能够正常转化，说明日期是正常的，通过
            if (Objects.isNull(date)){
                return false;
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat.format());
            String time = simpleDateFormat.format(date);
            if ("".equals(time)){
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
